package com.pmcc.utils;

import com.aliyuncs.*;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.push.model.v20160801.*;
import com.pmcc.core.entity.SmsRecord;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 阿里云短消息服务
 * @author yaonan
 * @Date 2018年11月20日
 */
public class SmsSendUtil {

    public static final String DEFAULT_CONNECT_TIMEOUT = "10000";//默认的链接超时时间
    public static final String DEFAULT_READ_TIMEOUT = "10000";//默认的读取超时时间
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    static  final  String accessKeyId= SystemPropertyUtil.getProperty("accessKeyId");
    static  final  String accessKeySecret= SystemPropertyUtil.getProperty("accessKeySecret");
    static  final  String verificationCode= SystemPropertyUtil.getProperty("templateCode1");//验证码
    static  final  String orderCode= SystemPropertyUtil.getProperty("templateCode2");//验证码
    static  final  String signName="云方便";

    public static IAcsClient acsClient=null;

    public static  IAcsClient getAcsClient() throws ClientException {
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        acsClient = new DefaultAcsClient(profile);
        return  acsClient;
    }
    public static SendSmsResponse sendSms(String telephone,String code,String str) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", DEFAULT_CONNECT_TIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", DEFAULT_READ_TIMEOUT);


        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(telephone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(code);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        request.setTemplateParam(str);
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");

        //hint 此处可能会抛出异常，注意catch
        getAcsClient();
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }

    /**
     * 模版1
     * @param telephone
     * @param message 验证码${code}，您正在进行身份验证，打死不要告诉别人哦！。
     * @return
     */
    public static SmsRecord sendSmsCode1(String telephone,String message){
        SendSmsResponse response = null;
        try {
            response = sendSms(telephone,verificationCode,message);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        SmsRecord smsRecord=new SmsRecord(message,verificationCode,telephone,response.getCode(),new Date(),0);
        return  smsRecord;
    }
    /**
     * 模版1
     * @param telephone
     * @param message 尊敬的${name}，你有新的任务单需要确认，快去云方便任务页面确认！
     * @return
     */
    public static SmsRecord sendSmsCode2(String telephone,String message){
        SendSmsResponse response = null;
        try {
            response = sendSms(telephone,orderCode,message);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        SmsRecord smsRecord=new SmsRecord(message,orderCode,telephone,response.getCode(),new Date(),0);
        return  smsRecord;
    }


    /**
     * 基础的推送信息到安卓
     * @param androidRequest
     * @param appKey
     * @param target
     * @param targetValue
     * @param title
     * @param body
     * @throws ClientException
     */
    public  static void basePushMessageToAndroid( PushMessageToAndroidRequest androidRequest, Long appKey, String target, String targetValue, String title, String body)throws ClientException {
        androidRequest.setProtocol(ProtocolType.HTTP);
        //内容较大的请求，使用POST请求
        androidRequest.setMethod(MethodType.POST);
        androidRequest.setAppKey(appKey);
        androidRequest.setTarget(target);
        androidRequest.setTargetValue(targetValue);
        androidRequest.setTitle(title);
        androidRequest.setBody(body);
        getAcsClient();
    }

    /**
     * 基础的推送通知到安卓
     * @param androidRequest
     * @param appKey
     * @param target
     * @param targetValue
     * @param title
     * @param body
     * @throws ClientException
     */
    public  static void basePushNoticeToAndroid(PushRequest androidRequest, Long appKey, String target, String targetValue, String title, String body)throws ClientException {

        androidRequest.setProtocol(ProtocolType.HTTP);
        //内容较大的请求，使用POST请求
        androidRequest.setMethod(MethodType.POST);
        androidRequest.setAppKey(appKey);
        androidRequest.setTarget(target);
        androidRequest.setTargetValue(targetValue);
        androidRequest.setTitle(title);
        androidRequest.setAndroidNotifyType("BOTH");
        androidRequest.setAndroidOpenType("NONE");
        androidRequest.setBody(body);
        androidRequest.setAndroidNotificationBarType(1);//通知栏自定义样式0-100
        androidRequest.setAndroidNotificationBarPriority(1);//通知栏自定义样式0-100
        androidRequest.setPushType("NOTICE");
        androidRequest.setDeviceType("ANDROID");
        getAcsClient();
    }

    /**
     * 封装的推送信息到安卓
     * @param appKey
     * @param target
     * @param targetValue
     * @param title
     * @param body
     * @return
     * @throws ClientException
     */
    public  static PushMessageToAndroidResponse pushMessageToAndroid(Long appKey,String target,String targetValue,String title,String body) throws ClientException {
        PushMessageToAndroidRequest androidRequest = new PushMessageToAndroidRequest();

        basePushMessageToAndroid(androidRequest,appKey,target,targetValue,title,body);
        PushMessageToAndroidResponse pushMessageToAndroidResponse = acsClient.getAcsResponse(androidRequest);
        return pushMessageToAndroidResponse;
    }

    /**
     *封装的推送通知到安卓
     */
    public static PushResponse pushNoticeToAndroid(Long appKey,String target,String targetValue,String title,String body,String ext) throws Exception {

        PushRequest androidRequest = new PushRequest();

        basePushNoticeToAndroid(androidRequest,appKey,target,targetValue,title,body);
        //ext格式"{\"k1\":\"v1\"}"
        androidRequest.setAndroidExtParameters(ext);

        PushResponse pushNoticeToAndroidResponse = acsClient.getAcsResponse(androidRequest);
        return pushNoticeToAndroidResponse;


    }
    /**
     * 查询短信详情
     * @param bizId 业务id
     * @param telephone 手机号
     * @return
     * @throws ClientException
     */
    public static QuerySendDetailsResponse querySendDetails(String bizId,String telephone) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", DEFAULT_CONNECT_TIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", DEFAULT_READ_TIMEOUT);

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(telephone);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    /**
     * 服务器异常短信通知
     * @param telephone
     */
    public static  void sendServerErrorNotice(String telephone){
        String code= SystemPropertyUtil.getProperty("serverErrorCode");
        SendSmsResponse response = null;
        try {
            response = sendSms(telephone,code,null);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws ClientException {

        try {
            String message = "{\"name\":\""+"王星"+"\"}";
            sendSmsCode2("13641837932",message);
        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}
